package br.com.app.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import br.com.app.modelo.Usuario;

public class UsuarioDAO extends DAOGenerico<Usuario, Long> {
	
	@SuppressWarnings("unchecked")
	public List<Usuario> buscar(int registro , int quantidade){
		EntityManager entityManager = EMF.get().createEntityManager();
		try{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append(" select c from Usuario c ");
			List<Usuario> Usuarios = null;
			Usuarios = entityManager.createQuery(stringBuilder.toString()).
			setFirstResult(registro).
			setMaxResults(quantidade).
			getResultList();
			Usuarios.size();
			return Usuarios;
		}catch( NoResultException e ){
            return null;
        } 
	}
	
	public int buscar(){
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(" select count(c) from Usuario c ");
		Number registros = null;
		EntityManager entityManager = EMF.get().createEntityManager();
		try{
			registros = (Number) entityManager.createQuery(stringBuilder.toString()).
									getSingleResult();
            return registros == null ? 0 : registros.intValue();
		}catch( NoResultException e ){
            return 0;
        }  
	}
	
	public Usuario autenticar(String email, String senha){
		EntityManager entityManager = EMF.get().createEntityManager();
		try{
			return (Usuario) entityManager.createQuery(" select u 				 " +
													   "   from Usuario u 		 " +
													   "  where u.email = :email " +
													   "    and u.senha = :senha ").
													   setParameter("email", email).
													   setParameter("senha", senha). 
													   getSingleResult();
		}catch( NoResultException e ){
            return null;
        } 
	}

}